package com.itcast.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itcast.reggie.commen.BaseContext;
import com.itcast.reggie.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class AnotherFilter implements Filter{
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取uri
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        //定义对比方法
        boolean check = check(uri);

        //获取访问ip,输出在控制台
       /* String remoteAddr = request.getRemoteAddr();
        log.info(remoteAddr);
        FileWriter Writer=new FileWriter("E://log.txt",true);
        Writer.write(remoteAddr);*/

        //判断是否放行
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        //判断是否登录
        Long employee = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("UserId");

        if(employee != null ){
            BaseContext.setCurrentId(employee);
            filterChain.doFilter(request,response);
            return;
        }

        if(userId != null ){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //啥都没.返回登录失败
        //filterChain.doFilter(request,response);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    //判断输入的请求是否在放行列表
    public boolean check(String url) {
        String[] urls = {"/employee/login", "/backend/**", "/front/**","/common/**","/user/login","/user/sendMsg","/user/login111"};
        for (String s : urls) {
            boolean match = PATH_MATCHER.match(s, url);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
